package com.springboot.leaseHouse.service;

import com.alibaba.fastjson.JSONObject;
import com.springboot.leaseHouse.bean.Loginer;
import com.springboot.leaseHouse.util.RedisUtil;
import nl.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.codec.digest.DigestUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @ClassName TokenService
 * @Description //TODO
 * @Author 秦野
 * @Date 2021/9/2410:24
 */
@Service
public class TokenService {
    @Resource
    private RedisUtil redisUtil;

    /**
     * 生成token 格式为token:设备-加密的用户名-时间-六位随机数
     * @param userAgentStr
     * @param loginerName 登录的用户名
     * @return 返回token
     */
    public String gererateToken(String userAgentStr, String loginerName){
        StringBuilder token = new StringBuilder("token:");
        //设备
        UserAgent userAgent = UserAgent.parseUserAgentString(userAgentStr);
        if(userAgent.getOperatingSystem().isMobileDevice()){
            token.append("MOBILE-");
        } else {
            token.append("PC-");
        }
        //加密用户名
        token.append(DigestUtils.md5Hex(loginerName) + "-");
        //时间
        token.append(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date()) + "-");
        //六位字符串
        token.append(new Random().nextInt(999999 - 111111 + 1) + 111111);
        //打印一下
        System.out.println(token.toString());

        return token.toString();
    }

    /**
     * 保存token到redis中
     * @param token 生成的token
     * @param loginer 登录的对象
     */
    public void save(String token, Loginer loginer){
        if(token.startsWith("token:PC")){
            this.redisUtil.setex(token, JSONObject.toJSONString(loginer), 2*60*60);
        } else {
            this.redisUtil.set(token, JSONObject.toJSONString(loginer));
        }
    }

}
